package cn.yj.syslog.aspect.error;

import cn.yj.commons.utils.StringUtils;
import cn.yj.syslog.aspect.OncePleaseOne;
import cn.yj.syslog.event.ErrorResponseEvent;
import cn.yj.syslog.service.ISysLogService;
import com.alibaba.fastjson.JSON;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-12-17 17:34
 */
@Component
public class ExceptionHandlerMethodInterceptor extends OncePleaseOne implements ApplicationEventPublisherAware {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlerMethodInterceptor.class);

    private static ApplicationEventPublisher publisher;

    @Override
    public Object doInvoke(MethodInvocation methodInvocation, HttpServletRequest request) throws Throwable {
        Object proceed = methodInvocation.proceed();
        if (!StringUtils.isNull(proceed)) {
            publisher.publishEvent(new ErrorResponseEvent(request, JSON.toJSONString(proceed)));
        }
        return proceed;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        publisher = applicationEventPublisher;
    }
}
